package databaseLayer;

import java.util.List;

import model.CinemaUser;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;

public class CinemaUser_db {
	public static boolean isUserExist(String username) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getThreadLocalSession();
			tx = session.beginTransaction();
			Query query = session
					.createQuery("from CinemaUser where username=:username");
			query.setString("username", username);
			List queryResult = query.list();
			if (queryResult.size() == 0 || queryResult.get(0) == null)
				return false;
			else
				return true;
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if (session != null)
				HibernateUtil.closeSession();
		}
		return false;
	}

	public static CinemaUser selectCinemaUserByUserName(String username) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getThreadLocalSession();
			tx = session.beginTransaction();
			Query query = session
					.createQuery("from CinemaUser where username=:username");
			query.setString("username", username);
			CinemaUser result = (CinemaUser) query.list().get(0);
			return result;
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if (session != null)
				HibernateUtil.closeSession();
		}
		return null;
	}

	public static List<CinemaUser> selectCinemaUsersByRole(String role) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getThreadLocalSession();
			tx = session.beginTransaction();
			Query query = session
					.createQuery("from CinemaUser where role=:role");
			query.setString("role", role);
			List<CinemaUser> result = query.list();
			return result;
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if (session != null)
				HibernateUtil.closeSession();
		}
		return null;
	}
}
